package com.octant.testipc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.home.sdk.builder.TuyaCameraActivatorBuilder;
import com.tuya.smart.sdk.api.ITuyaActivatorGetToken;
import com.tuya.smart.sdk.api.ITuyaCameraDevActivator;
import com.tuya.smart.sdk.api.ITuyaSmartCameraActivatorListener;
import com.tuya.smart.sdk.bean.DeviceBean;

import java.util.Hashtable;

import androidx.appcompat.app.AppCompatActivity;

import static android.graphics.Color.BLACK;

public class DeviceConfigQrcodeActivity extends AppCompatActivity implements View.OnClickListener {

    private RelativeLayout rl_start_page,rl_set_wifi,rl_show_bitmap,rl_connect_device;
    private Button btn_set_wifi,btn_switch_wifi,btn_show_bitmap,btn_connect_device,btn_complete,btn_cancel;
    private TextView tv_wifi_name;
    private EditText edt_wifi_password;
    private ImageView iv_qrcode;
    private Context mContext;
    private WifiBroadcastReceiver wifiReceiver;
    private WifiManager wifiManager;

    private ITuyaCameraDevActivator mTuyaActivator;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_config_qrcode);
        mContext = DeviceConfigQrcodeActivity.this;
        initViews();
        wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
    }

    private void initViews(){
        rl_start_page = findViewById(R.id.rl_start_page);
        rl_set_wifi = findViewById(R.id.rl_set_wifi);
        rl_show_bitmap = findViewById(R.id.rl_show_bitmap);
        rl_connect_device = findViewById(R.id.rl_connect_device);
        btn_set_wifi = findViewById(R.id.btn_set_wifi);
        btn_switch_wifi = findViewById(R.id.btn_switch_wifi);
        btn_show_bitmap = findViewById(R.id.btn_show_bitmap);
        tv_wifi_name = findViewById(R.id.tv_wifi_name);
        edt_wifi_password = findViewById(R.id.edt_wifi_password);
        iv_qrcode = findViewById(R.id.iv_qrcode);
        btn_connect_device = findViewById(R.id.btn_connect_device);
        btn_complete = findViewById(R.id.btn_complete);
        btn_cancel = findViewById(R.id.btn_cancel);

        btn_set_wifi.setOnClickListener(this);
        btn_switch_wifi.setOnClickListener(this);
        btn_show_bitmap.setOnClickListener(this);
        btn_connect_device.setOnClickListener(this);
        btn_complete.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);

        showPage(0);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        wifiReceiver = new WifiBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);//监听wifi连接状态广播,是否连接了一个有效路由
        registerReceiver(wifiReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(wifiReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTuyaActivator != null) {
            mTuyaActivator.onDestroy();
        }
    }

    private void showPage(int page){
        switch (page){
            case 0:{
                rl_start_page.setVisibility(View.VISIBLE);
                rl_set_wifi.setVisibility(View.GONE);
                rl_show_bitmap.setVisibility(View.GONE);
                rl_connect_device.setVisibility(View.GONE);
            }break;
            case 1:{
                rl_start_page.setVisibility(View.GONE);
                rl_set_wifi.setVisibility(View.VISIBLE);
                rl_show_bitmap.setVisibility(View.GONE);
                rl_connect_device.setVisibility(View.GONE);
            }break;
            case 2:{
                rl_start_page.setVisibility(View.GONE);
                rl_set_wifi.setVisibility(View.GONE);
                rl_show_bitmap.setVisibility(View.VISIBLE);
                rl_connect_device.setVisibility(View.GONE);
            }break;
            case 3:{
                rl_start_page.setVisibility(View.GONE);
                rl_set_wifi.setVisibility(View.GONE);
                rl_show_bitmap.setVisibility(View.GONE);
                rl_connect_device.setVisibility(View.VISIBLE);
            }break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_set_wifi:{
                showPage(1);
                setWifiNameView();
            }break;
            case R.id.btn_switch_wifi:{
                Intent intent = new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK);
                startActivity(intent);
            }break;
            case R.id.btn_show_bitmap:{
                String ssid = tv_wifi_name.getText().toString();
                String password = edt_wifi_password.getText().toString();
                if (ssid == null || ssid.isEmpty()){
                    Toast.makeText(mContext, "WiFi名称不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password == null || password.isEmpty()){
                    Toast.makeText(mContext, "WiFi密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                getActivatorToken(ssid,password);
            }break;
            case R.id.btn_connect_device:{
                showPage(3);
                mTuyaActivator.start();
                btn_complete.setVisibility(View.GONE);
                btn_cancel.setVisibility(View.VISIBLE);
            }break;
            case R.id.btn_complete:{
                mTuyaActivator.stop();
                finish();
            }break;
            case R.id.btn_cancel:{
                mTuyaActivator.stop();
                finish();
            }break;
        }
    }

    private void getActivatorToken(String ssid,String password){
        TuyaHomeSdk.getActivatorInstance().getActivatorToken(HomeUtil.getInstance().homeBean.getHomeId(),
                new ITuyaActivatorGetToken() {

                    @Override
                    public void onSuccess(String token) {
                        initTuyaActivator(token,ssid,password,100);
                        mTuyaActivator.createQRCode();
                    }

                    @Override
                    public void onFailure(String s, String s1) {
                        Toast.makeText(mContext, ""+s1, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void initTuyaActivator(String token,String ssid,String password,long timeout){
        TuyaCameraActivatorBuilder builder = new TuyaCameraActivatorBuilder()
                .setContext(mContext)
                .setSsid(ssid)
                .setPassword(password)
                .setToken(token)
                .setTimeOut(timeout)
                .setListener(new ITuyaSmartCameraActivatorListener() {
                    @Override
                    public void onQRCodeSuccess(String qrcodeUrl) {
                        //返回生成二维码的 URL 链接
                        showPage(2);
                        try {
                            Bitmap bitmap = createQRCode(qrcodeUrl,300);
                            iv_qrcode.setImageBitmap(bitmap);
                        } catch (WriterException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(String errorCode, String errorMsg) {
                        //配网失败
                        Toast.makeText(mContext, "配网失败。"+errorMsg, Toast.LENGTH_SHORT).show();
                        btn_complete.setVisibility(View.VISIBLE);
                        btn_cancel.setVisibility(View.GONE);
                    }

                    @Override
                    public void onActiveSuccess(DeviceBean devResp) {
                        //配网成功
                        Toast.makeText(mContext, "配网成功", Toast.LENGTH_SHORT).show();
                        btn_complete.setVisibility(View.VISIBLE);
                        btn_cancel.setVisibility(View.GONE);
                        HomeUtil.getInstance().getHomeDetail(HomeUtil.getInstance().homeBean.getHomeId());
                    }
                });

        mTuyaActivator = TuyaHomeSdk.getActivatorInstance().newCameraDevActivator(builder);
    }

    public static Bitmap createQRCode(String url, int widthAndHeight)
            throws WriterException {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN,0);
        BitMatrix matrix = new MultiFormatWriter().encode(url,
                BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight, hints);

        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    //监听wifi状态
    public class WifiBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())){
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);

                if(NetworkInfo.State.DISCONNECTED == info.getState()){//wifi没连接上
                    setWifiNameView();
                }else if(NetworkInfo.State.CONNECTED == info.getState()){//wifi连接上了
                    setWifiNameView();
                }else if(NetworkInfo.State.CONNECTING == info.getState()){//正在连接

                }
            }
        }
    }

    public void setWifiNameView(){
        WifiInfo connectedWifiInfo = wifiManager.getConnectionInfo();
        String ssid = connectedWifiInfo.getSSID();
        if (ssid!=null && ssid.length()>2) {
            ssid = ssid.substring(1);
            ssid = ssid.substring(0, ssid.length() - 1);
            tv_wifi_name.setText("" + ssid);
        }else {
            tv_wifi_name.setText("");
        }
    }
}
